/**
 * 
 */
package edu.sjtu.se.prophet.io.gson;

import java.lang.reflect.Type;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

import edu.sjtu.se.prophet.graph.Edge;
import edu.sjtu.se.prophet.graph.Graph;
import edu.sjtu.se.prophet.graph.Node;

/**
 * @author willard
 * 
 */
public class GraphSerializer implements JsonSerializer<Graph> {

    @Override
    public JsonElement serialize(Graph graph, Type type,
            JsonSerializationContext context) {

        JsonObject graphObject = new JsonObject();
        graphObject.add("meta", context.serialize(graph.getMeta()));

        JsonArray nodesArray = new JsonArray();
        for (Node node : graph.getNodes()) {
            nodesArray.add(context.serialize(node));
        }
        graphObject.add("nodes", nodesArray);

        JsonArray edgesArray = new JsonArray();
        for (Edge edge : graph.getEdges()) {
            edgesArray.add(context.serialize(edge));
        }
        graphObject.add("edges", edgesArray);

        return graphObject;
    }

}
